#!/bin/bash
#export VER=5.10.58
export VER=$1
#export COMPILER=../../../gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-
compdir=$(cd "$2"; pwd)
export COMPILER=$compdir/bin/aarch64-linux-gnu-

export LVER=-aml-s905d

mkdir build >/dev/null 2>&1
cd build
echo "Extracing kernel source ..."
tar xf linux-$VER.tar.xz
cd linux-$VER

echo "Applying patch ..."
# apply all patches, required for n1 default uboot
#for p in `ls ../../patch`; do patch --ignore-whitespace -t -p1 -N < ../../patch/$p; done

# only need to apply high load patch if new uboot installed
patch --ignore-whitespace -t -p1 -N < ../../patch/0001-fix-n1-high-load.patch

cp ../../default.config ./.config
echo "Generating config ..."
make -j8 ARCH=arm64 CROSS_COMPILE=$COMPILER LOCALVERSION="$LVER" olddefconfig

echo "Building kernel ..."
make -j8 ARCH=arm64 CROSS_COMPILE=$COMPILER LOCALVERSION="$LVER" bindeb-pkg

# collect build target files
cd ..
mkdir target.$VER
cd target.$VER
cp ../linux-$VER/arch/arm64/boot/Image ./
mkdir dtb
cp ../linux-$VER/arch/arm64/boot/dts/amlogic/*-phicomm-n1.dtb dtb/
mv ../*$LVER* ./

echo "Building boot files ..."
mkimage  -C none -A arm -T script -d ../../boot/s905_autoscript.src s905_autoscript
mkimage  -C none -A arm -T script -d ../../boot/emmc_autoscript.src emmc_autoscript

cp ../../boot/u-boot.ext ./
cp -r ../../boot/extlinux ./

echo "Build completed. Boot and kernel files are in build/target.$VER"
